# 项目初始化文件
import logging
import os
from logging.handlers import RotatingFileHandler

from celery import Celery
from flask import Flask

from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
# from flask.logging import default_handler

from application import settings
from application.settings.dev import DevelopmentConfig
from application.settings.prop import ProductionConfig
from application.settings import Config


# config = {
#     'dev': DevelopmentConfig,
#     'pro': ProductionConfig,
#
# }

# 增加日志模块
def setup_log(app, Config):
    # 在 DEBUG 模式下，使用 StreamHandler，并使用 DEBUG 级别，这样可以将所有的信息都输出到控制台
    if Config.LOG_LEVEL == 'DEBUG':
        app.logger.root.setLevel('DEBUG')
        log_handler = logging.StreamHandler()
        log_handler.setFormatter(
            logging.Formatter('[%(asctime)s] %(levelname)s in %(module)s.%(funcName)s : %(message)s'))
        app.logger.root.addHandler(log_handler)

    else:
        # 不使用 StreamHandler 的原因，是 uwsgi 可能会在标准输出中加入它自己的 Log，为了避免Log被弄乱，单独使用一个 FileHandler
        logging.basicConfig(level=Config.LOG_LEVEL)
        # 不在使用时间切分方式，多线程支持不好
        log_handler = RotatingFileHandler(Config.LOG_DIR, maxBytes=1024 * 1024 * 10, backupCount=10)

        log_handler.setFormatter(
            logging.Formatter('[%(asctime)s] %(levelname)s in %(module)s.%(funcName)s : %(message)s'))
        logging.getLogger().addHandler(log_handler)


def set_env(env):
    # open('application/settings/__init__.py', 'w',encoding='utf8').write(re.sub(r"dev", "pro", open('application/settings/__init__.py',encoding='utf8').read()))
    f = open('application/settings/__init__.py', 'r', encoding='utf8')
    f1 = open('application/settings/__init__1.py', 'w', encoding='utf8')
    data = f.readlines()
    env_str = ""
    for i in data:
        if "ENV =" in i:
            env_str += "    ENV = '%s'\n" % env
        else:
            env_str += i

    f1.write(env_str)
    f.close()
    f1.close()
    os.remove('application/settings/__init__.py')
    os.rename('application/settings/__init__1.py', 'application/settings/__init__.py')


redis_store = None


# 创建数据库连接对象
# def new_session():
#     dbSQLAlchemy = SQLAlchemy()
#     return dbSQLAlchemy

db = SQLAlchemy()


def make_celery(app):
    celery = Celery(app.import_name,
                    broker=app.config['CELERY_BROKER_URL'],
                    backend=app.config['CELERY_BACKEND_URL'])
    celery.conf.update(app.config)
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask
    return celery

def doctor_():
    import flask_sqlalchemy
    if flask_sqlalchemy.__version__ != '2.4.1':
        raise Exception('flask_sqlalchemy 版本错误！包已升级->2.4.1，请更新到指定版本。')
    
def init_app():
    '项目初始化'
    # 主应用的根目录
    doctor_()
    app = Flask('QA平台-守卫者')

    # 加载配置
    app.config.from_object(Config)

    # redis的连接初始化
    # global redis_store
    # redis_store=StrictRedis(host=Config.REDIS_HOST,port=Config.REDIS_PORT,db=0)

    # 开启CSRF防范
    # CSRFProtect(app)

    # from flask_cors import CORS
    # CORS(app, supports_credentials=True)
    
    # 开启跨域
    from flask_cors import CORS
    CORS(app, supports_credentials=True)
    
    # 开启session
    Session(app)

    # 增加数据库连接
    db.init_app(app)

    # 启用日志
    setup_log(app, Config)

    # 注册蓝图
    from .apps.index import index_blu
    from .apps.ci import ci
    from .apps.mock import mock
    from .apps.case_library import case_library
    from .apps.d_bot import d_bot
    from .apps.nodes import node
    from .apps.plan_task import plan_task
    from .apps.user import user
    from .apps.report import report
    from .apps.group import group
    from .apps.project import project
    from .apps.quality_control import quality_control
    from .apps.project_version import project_version
    from .apps.mantis_bug import mantis_bug
    from .apps.bug_reopen import bug_reopen
    from .apps.collect import collect


    # 路由绑定
    app.register_blueprint(index_blu, url_prefix='')
    app.register_blueprint(ci, url_prefix='/ci')
    app.register_blueprint(mock, url_prefix='/mock')
    app.register_blueprint(case_library, url_prefix='/case_library')
    app.register_blueprint(d_bot, url_prefix='/d_bot')
    app.register_blueprint(node, url_prefix='/node')
    app.register_blueprint(plan_task, url_prefix='/plan_task')
    app.register_blueprint(user, url_prefix='/user')
    app.register_blueprint(report, url_prefix='/report')
    app.register_blueprint(group, url_prefix='/group')
    app.register_blueprint(project, url_prefix='/project')
    app.register_blueprint(quality_control, url_prefix='/quality_control')
    app.register_blueprint(project_version, url_prefix='/project_version')
    app.register_blueprint(mantis_bug, url_prefix='/mantis_bug')
    app.register_blueprint(bug_reopen, url_prefix='/bug_reopen')
    app.register_blueprint(collect, url_prefix='/collect')



    return app
